import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ProfileServiceProxy, DataItemServiceProxy, DataItemViewDto } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { IOrganizationUnitsTreeComponentData, OrganizationUnitsTreeComponent } from '../../shared/organization-unit-tree.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'DataItemCreate',
  templateUrl: './DataItemCreate.component.html',
  styleUrls: ['./DataItemCreate.component.css']
})
export class DataItemCreateComponent extends AppComponentBase {
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
  active = false;
  saving = false;
  ItemView: DataItemViewDto = new DataItemViewDto();
  constructor(injector: Injector,
    private _dataItemServiceProxy: DataItemServiceProxy,
    private _profileService: ProfileServiceProxy) {
    super(injector);
  }
  show(ItemId?: string): void {
    console.log(ItemId)
    if (!ItemId) {
      this.active = true;
    }

    if (ItemId === undefined){
      this.modal.show();
    } else {
      this._dataItemServiceProxy.getDataItemForEdit(ItemId).subscribe(resultdata => {
        this.ItemView = resultdata;
        console.log(resultdata);
        if (ItemId) {
          this.active = true;
        }
        this.modal.show();
      });
    }
    // this.active = true;
    // this.modal.show();
  }
  onShown(): void {

  }
  save(): void {
    this.saving = true;

    if (!!this.ItemView.id) {
      this._dataItemServiceProxy.updateDataItem(this.ItemView)
        .pipe(finalize(() => { this.saving = false; }))
        .subscribe(() => {
          this.notify.info(this.l('SavedSuccessfully'));
          this.close();
          this.modalSave.emit(null);
        });
    } else {
      // let input = new DataItemModel();
      // input.itemCode = this.ItemView.itemCode;
      // input.itemName = this.ItemView.itemName;
      // input.description = this.ItemView.description;
      this.ItemView.id = undefined;
      console.log(this.ItemView);
      this._dataItemServiceProxy.createDataItem(this.ItemView)
        .pipe(finalize(() => { this.saving = false; }))
        .subscribe(() => {
          this.notify.info(this.l('SavedSuccessfully'));
          this.close();
          this.modalSave.emit(null);
        });
    }
  }

  close(): void {
    this.ItemView = new DataItemViewDto();
    this.active = false;
    this.modal.hide();
  }
}

